package com.open.capacity.common.controller;

import com.open.capacity.common.FileService;
import com.open.capacity.commons.Result;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.file.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

/**
 * 上传文件
 *
 * @author ftquan
 */
@RestController
public class UploadController {
    private static final Logger log = LoggerFactory.getLogger(UploadController.class);

    @Value("${file.uploadpath:/usr/local/files/upload}")
    private String fileuploadPath;


    @Autowired
    private FileService fileService;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
//            if (!FileUtils.isValidFilename(fileName)) {
//                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
//            }
            String realFileName = fileName.substring(fileName.lastIndexOf("/") + 1);
            String filePath = fileuploadPath + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    @ResponseBody
    public Result uploadFile(MultipartFile file) {
        String url = null;
        try {
            url = fileService.upload(file);
            return Result.succeed(url, "上传成功");
        } catch (IOException e) {
            log.error("上传文件失败[{}]", e.getMessage());
            return Result.failed("上传失败");
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload2")
    public String uploadFile2(MultipartFile uploadFile) {
        String url = null;
        try {
            url = fileService.upload(uploadFile);
            return url;
        } catch (IOException e) {
            log.error("上传文件失败[{}]", e.getMessage());
            return null;
        }
    }

    @PostMapping("/common/upload/base64")
    @ResponseBody
    public Result<String> saveBase64(@RequestParam(value = "file") String base64Str) {
        if (StringUtils.isBlank(base64Str)) {
            return Result.failed("file不可缺省");
        } else if (base64Str.indexOf("data:image/png;") != -1) {
            base64Str = base64Str.replace("data:image/png;base64,", "");
        } else if (base64Str.indexOf("data:image/jpeg;") != -1) {
            base64Str = base64Str.replace("data:image/jpeg;base64,", "");
        } else if (base64Str.indexOf("data:image/jpg;") != -1) {
            base64Str = base64Str.replace("data:image/jpg;base64,", "");
        } else {
            return Result.failed("请选择.png或者.jpg格式的图片");
        }
        String url;
        try {
            url = fileService.uploadBase64(base64Str);
        } catch (IOException e) {
            log.error("上传文件失败[{}]", e.getMessage());
            return Result.failed("上传失败");
        }
        return Result.succeed(url, "上传成功");
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 本地资源路径
        String localPath = fileuploadPath;
        // 数据库资源地址
        String downloadPath = localPath + StringUtil.substringAfter(resource, "profile");
        // 下载名称
        String downloadName = StringUtil.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }
}
